package com.licq.hongmeng.net;


import com.licq.hongmeng.utils.Constants;
import com.parkingwang.okhttp3.LogInterceptor.LogInterceptor;

import ohos.agp.render.render3d.BuildConfig;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * retrofit单例
 */
public class RetrofitUtil {

    private Retrofit retrofit;

    private RetrofitUtil() {
        initRetrofit();
    }

    public static RetrofitUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final RetrofitUtil INSTANCE = new RetrofitUtil();
    }

    private void initRetrofit() {
        // 添加Header拦截器
        HttpCommonInterceptor commonInterceptor = new HttpCommonInterceptor.Builder()
//                .addHeaderParams("id", DeviceInfo.getInstance(ApplicationData.mApplication).getIMEI())
//                .addHeaderParams("model", DeviceInfo.getInstance(ApplicationData.mApplication).getDeviceType())
//                .addHeaderParams("channel", DeviceInfo.getInstance(ApplicationData.mApplication).getChannel())
//                .addHeaderParams("version", DeviceInfo.getInstance(ApplicationData.mApplication).getOsVersion())
//                .addHeaderParams("display", DeviceInfo.getInstance(ApplicationData.mApplication).getDisplay())
//                .addHeaderParams("appversion", DeviceInfo.getInstance(ApplicationData.mApplication).getVersionCode() + "")
                .build();

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(commonInterceptor);
        if (BuildConfig.DEBUG) {
            builder.addNetworkInterceptor(new LogInterceptor());
        }

        if (StringUtils.isNoneEmpty(Constants.BASEURL)) {
            try {
                // 单向认证
                builder.sslSocketFactory(SSLSocketFactoryUtils.getOnewaySSLSocketFactory());
                builder.hostnameVerifier(new SSLSocketFactoryUtils.AppHostnameVerifier());

                // 双向认证,需要在工具类中设置对应的属性才可以使用
                // builder.sslSocketFactory(SSLSocketFactoryUtils.getTwowaySSLCertifcation(ApplicationData.mApplicationData));
                // builder.hostnameVerifier(new SSLSocketFactoryUtils.AppHostnameVerifier());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(Constants.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service) {
        return retrofit.create(service);
    }


}
